package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishVO;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ttao
 * @since 2023/4/23 11:22
 */

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据分类查询菜品数量
     *
     * @param categoryId
     * @return
     */
    @Override
    public Integer countByCategoryId(Long categoryId) {
        return dishMapper.countByCategoryId(categoryId);
    }

    /**
     * 菜品管理分页条件查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryPage(DishPageQueryDTO dishPageQueryDTO) {
        // 设置分页条件
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.queryPage(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 添加菜品
     *
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public int saveWithFlavor(DishDTO dishDTO) {
        // 组装dish对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 菜品表插入数据
        dishMapper.insert(dish);

        // 返回添加成功的主键id值
        Long dishId = dish.getId();

        // 获取口味列表
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();

        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            dishFlavorList.forEach(dishFlavor -> {
                // 菜品口味关系表 关联菜品id
                dishFlavor.setDishId(dishId);
            });
        }

        // 向口味表插入n条数据
        return dishFlavorService.insertBatch(dishFlavorList);
    }

    /**
     * 菜品批量删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int

    deleteByIds(List<Long> ids) {
        //判断当前菜品是否能够删除---是否存在起售中的菜品？？
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            Integer status = dish.getStatus();
            if (status == 1) {
                // 关联起售的菜品,不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前菜品是否能够删除---是否被套餐关联了？？
        List<Long> setmealIds = setmealDishService.selectsetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            // 当前菜品关联了套餐,不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 删除菜品关联的口味数据
        dishFlavorService.deleteByDishIds(ids);

        // 删除菜品表中的菜品数据
        return dishMapper.deleteByIds(ids);
    }

    /**
     * 根据id查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    @Override
    public DishVO selectByIdWithFlavor(Long id) {
        // 根据id查询菜品数据
        Dish dish = dishMapper.selectById(id);

        // 根据id查询菜品关联的口味
        List<DishFlavor> dishFlavorList = dishFlavorService.selectByDishId(id);

        // 将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public int updateWithFlavor(DishDTO dishDTO) {
        // 组装数据对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //修改菜品表基本信息
        dishMapper.updateById(dish);

        // 更新 套餐菜品表中的关联数据(修改菜品的名称,价格,份数)
        SetmealDish setmealDish = new SetmealDish();
        setmealDish.setDishId(dishDTO.getId());
        setmealDish.setName(dish.getName());
        setmealDish.setPrice(dish.getPrice());
        setmealDishService.updateByDishId(setmealDish);

        //删除原有的口味数据
        List<Long> dishIds = new ArrayList<>();
        dishIds.add(dish.getId());
        dishFlavorService.deleteByDishIds(dishIds);

        // 重新插入口味数据
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();

        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });

            // 向口味表批量插入数据
            return dishFlavorService.insertBatch(dishFlavorList);
        }

        return 1;
    }


    /**
     * 启用、禁用菜品"
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public int startOrStop(Integer status, Long id) {
        if (status.equals(StatusConstant.DISABLE)) {
            // 判断套餐是否停售
            List<SetmealDish> setmealDishList = setmealDishService.selectByDishId(id);
            for (SetmealDish setmealDish : setmealDishList) {
                Setmeal setmeal = setmealService.selectById(setmealDish.getSetmealId());
                if (setmeal.getStatus().equals(StatusConstant.ENABLE)) {
                    throw new DishEnableFailedException(MessageConstant.DISH_DISABLE_FAILED);
                }
            }
        }

        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        return dishMapper.updateById(dish);
    }

    /**
     * 根据分类id查询对应菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> selectByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }

    /**
     * 根据 id查询菜品
     *
     * @param id
     */
    @Override
    public Dish selectById(Long id) {
        return dishMapper.selectById(id);
    }

    /**
     * 条件查询菜品和口味
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        // 封装dish对象
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        // 构建dishVOList集合
        List<DishVO> dishVOList = new ArrayList<>();
        // 根据categoryId查询菜品集合
        List<Dish> dishList = dishMapper.list(dish);
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> dishFlavorList = dishFlavorService.selectByDishId(d.getId());
            dishVO.setFlavors(dishFlavorList);
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }
}
